include('shared.lua')

local BeamMat = Material("effects/mining_beam/mining_laser")
BeamMat:SetMaterialInt("$spriterendermode",0)
BeamMat:SetMaterialInt("$illumfactor",8)
BeamMat:SetMaterialFloat("$alpha",1)
BeamMat:SetMaterialInt("$nocull",1)
local FlareMat = Material("sprites/light_glow01")
FlareMat:SetMaterialInt("$spriterendermode",0)
FlareMat:SetMaterialInt("$illumfactor",8)
FlareMat:SetMaterialFloat("$alpha",0.7)
FlareMat:SetMaterialInt("$nocull",1)

SWEP.PrintName = "Personal Mining Device"
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = true
SWEP.Slot = 3
SWEP.SlotPos = 3

local LASER = Material('effects/mining_laser')

function SWEP:Initialize()
    local ply = LocalPlayer()
    self.VM = ply:GetViewModel()
    local attachmentIndex = self.VM:LookupAttachment("muzzle")
    if attachmentIndex == 0 then attachmentIndex = self.VM:LookupAttachment("1") end
	self.Attach = attachmentIndex
end

function SWEP:ViewModelDrawn()
	if(self.Weapon:GetNWBool("Active")) then
        //Draw the laser beam.
        local pos = self.Owner:GetShootPos()
		local ang = self.Owner:GetAimVector()
		local tracedata = {}
		tracedata.start = pos
		tracedata.endpos = pos+(ang*128)
		tracedata.filter = self.Owner
		local trace = util.TraceLine(tracedata)

		target = trace.Entity

		render.SetMaterial( BeamMat )
		render.DrawBeam(self.VM:GetAttachment(self.Attach).Pos, trace.HitPos, 3+(math.Rand(-0.5,0.5)), 0, 0, Color(255, 0, 0, 255))
		
		render.SetMaterial( FlareMat )
		render.DrawSprite( self.VM:GetAttachment(self.Attach).Pos + (ang * 10), 10+(2*math.Rand(-1,1)), 10+(2*math.Rand(-1,1)), Color(255, 50, 50, 255) )
		
		if trace.Hit then
			render.SetMaterial( FlareMat )
			render.DrawSprite( trace.HitPos, 10+(2*math.Rand(-1,1)), 10+(2*math.Rand(-1,1)), Color(255, 50, 50, 255) )
		
			//Sparkies
			local sparks = EffectData()
			sparks:SetOrigin(trace.HitPos)
			sparks:SetNormal(trace.HitNormal)
			sparks:SetMagnitude( 1 )
            sparks:SetScale( 1 )
            sparks:SetRadius( 2 )
			util.Effect("Sparks",sparks)
		end
	end
end
